import { cleanOperlog, delOperlog, listOperlog } from '@/api/system/operlog'

import { addDateRange, formatDate } from '@/utils/common'
import { useDicts } from '@/utils/dict'
import { downloadFile } from '@/utils/http'
import { message } from '@/utils/message'
import type { PaginationProps } from '@pureadmin/table'
import { type DateModelType, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, toRefs } from 'vue'

export function useOperLog() {
  const data = reactive({
    form: {},
    queryParams: {
      title: undefined,
      operName: undefined,
      businessType: undefined,
      status: undefined,
    },
  })
  const { form, queryParams } = toRefs(data)
  const operId = ref(0)
  const title = ref('')
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const dataList = ref([])
  const loading = ref(true)
  const showSelection = true
  const dateRange = ref<DateModelType>(null)
  const formDialogVisible = ref(false)
  const { sys_oper_type, sys_common_status } = useDicts('sys_oper_type', 'sys_common_status')
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  })
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: 55,
      align: 'left',
      hide: ({ checkList }) => !checkList.includes('勾选列'),
    },
    {
      label: '序号',
      type: 'index',
      width: 70,
      hide: ({ checkList }) => !checkList.includes('序号列'),
    },
    {
      label: '日志编号',
      prop: 'operId',
      minWidth: 80,
    },
    {
      label: '系统模块',
      prop: 'title',
      minWidth: 120,
    },
    {
      label: '操作类型',
      prop: 'businessType',
      minWidth: 120,
      cellRenderer: (scope) => {
        return <DictTag options={sys_oper_type} value={scope.row.businessType} />
      },
    },
    {
      label: '请求方式',
      prop: 'requestMethod',
      minWidth: 120,
    },
    {
      label: '操作人员',
      prop: 'operName',
      minWidth: 120,
    },
    {
      label: '主机',
      prop: 'operIp',
      minWidth: 150,
    },
    {
      label: '状态',
      prop: 'status',
      minWidth: 100,
      cellRenderer: (scope) => {
        return <DictTag options={sys_common_status} value={scope.row.status} />
      },
    },
    {
      label: '操作时间',
      minWidth: 180,
      prop: 'operTime',
      formatter: ({ operTime }) => formatDate(operTime),
    },
    {
      label: '操作',
      fixed: 'right',
      width: 150,
      slot: 'operation',
    },
  ]

  /** 详细按钮操作 */
  function handleView(row) {
    title.value = '操作日志详情'
    form.value = row
    formDialogVisible.value = true
  }

  /** 导出按钮操作 */
  function handleExport() {
    downloadFile(
      'system/operlog/export',
      {
        ...queryParams.value,
      },
      `操作日志.xlsx`
    )
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const operIds = row.operId || ids.value
    ElMessageBox.confirm('数据一经删除不可恢复，请再次确认！', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await delOperlog(operIds)
      message('删除成功', { type: 'success' })
      onSearch()
    })
  }

  /** 清空按钮操作 */
  function handleClean() {
    ElMessageBox.confirm('是否确认清空所有操作日志数据项?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await cleanOperlog()
      message('清空所有操作日志成功', { type: 'success' })
      onSearch()
    })
  }

  /** 改变分页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  /** 改变当前分页 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  /** 改变多选项 */
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.operId)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 搜索按钮操作 */
  async function onSearch() {
    loading.value = true
    const params = {
      ...queryParams.value,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
    const { rows, total } = await listOperlog(addDateRange(params, dateRange.value))
    dataList.value = rows
    pagination.total = total
    loading.value = false
  }

  /** 重置按钮操作 */
  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    dateRange.value = null
    onSearch()
  }

  onMounted(() => {
    onSearch()
  })

  return {
    form,
    title,
    operId,
    loading,
    columns,
    multiple,
    dateRange,
    dataList,
    pagination,
    queryParams,
    showSelection,
    formDialogVisible,
    sys_common_status,
    sys_oper_type,
    onSearch,
    resetForm,
    handleView,
    handleClean,
    handleDelete,
    handleExport,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
  }
}
